package com.lcifn.middleware.rpc.transport.coder;

import com.lcifn.middleware.rpc.transport.command.Command;
import com.lcifn.middleware.rpc.transport.command.Header;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Commander编码
 * @author lichao
 * @date 2021/2/1 15:55
 */
public abstract class CommandEncoder extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception {
        if (!(msg instanceof Command)) {
            throw new Exception(String.format("Unknown type: %s!", msg.getClass().getCanonicalName()));
        }

        Command command = (Command) msg;
        // 包长度(4 + header长度 + payload长度)
        byteBuf.writeInt(Integer.BYTES + command.getHeader().length() + command.getPayload().length);
        // Header内容
        encodeHeader(command.getHeader(), byteBuf);
        // Payload内容
        byteBuf.writeBytes(command.getPayload());
    }

    /**
     * Header编码
     * @param header
     * @param byteBuf
     */
    protected void encodeHeader(Header header, ByteBuf byteBuf) {
        byteBuf.writeInt(header.getRequestId());
        byteBuf.writeInt(header.getType());
        byteBuf.writeInt(header.getVersion());
    }
}
